<template>
  <div class="role-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">角色管理</h1>
          <p class="page-subtitle">管理系统角色及其权限配置</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" size="large" @click="handleAddRole">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <el-card class="table-card">
        <el-table
          :data="roleList"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#475569',
            fontWeight: '600',
            fontSize: '14px'
          }"
          :row-style="{ height: '60px' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="name" label="角色名称">
            <template #default="{ row }">
              <div class="role-name">
                <el-icon class="role-icon"><Avatar /></el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="key" label="角色标识" width="120" />
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column label="权限分类" min-width="220" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ getRolePermissionNames(row.key) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户数量" width="120" align="center">
            <template #default="{ row }">
              <div class="user-count">
                <el-icon class="user-icon"><User /></el-icon>
                <span class="count-number">{{ userStats[row.key] || 0 }}</span>
                <span class="count-label">人</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'danger'" size="small">
                {{ row.status === 0 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-info">
                <el-icon class="time-icon"><Clock /></el-icon>
                <span>{{ row.created_at }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" plain @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="info" 
                  plain 
                  @click="handleViewUsers(row)"
                  :disabled="(userStats[row.key] || 0) === 0"
                >
                  <el-icon><User /></el-icon>
                  查看用户
                </el-button>
                <el-button size="small" type="danger" plain @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="600px"
      class="role-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        label-position="top"
        class="role-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色标识" prop="key">
              <el-input v-model="roleForm.key" placeholder="请输入角色标识" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="显示顺序">
              <el-input-number v-model="roleForm.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="roleForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" :value="0" />
                <el-option label="停用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="角色权限" prop="permissions">
          <div class="permission-tree">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionTreeData"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              default-expand-all
              class="custom-tree"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '创建角色' : '保存修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Avatar, Clock, Edit, Delete, User } from '@element-plus/icons-vue'
import { 
  getRoleList, 
  createRole, 
  updateRole, 
  deleteRole, 
  getRoleDetail,
  type Role,
  type RoleForm,
  type RoleListParams
} from '@/api/role'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const userStore = useUserStore()

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 角色列表
const roleList = ref<Role[]>([])
const loading = ref(false)

// 用户统计数据
const userStats = ref<Record<string, number>>({})

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const roleFormRef = ref()
const permissionTreeRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 角色表单
const roleForm = reactive<RoleForm>({
  id: undefined,
  name: '',
  key: '',
  description: '',
  status: 0,
  sort: 0,
  permissions: []
})

// 权限树数据
type PermissionTreeNode = { id: string; label: string; children?: PermissionTreeNode[] }
const permissionTreeData = ref<PermissionTreeNode[]>([])

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 路由权限映射：key 为路由的 name，label 为显示名称
const permissionOptions = ref<{ key: string; label: string; parent?: string }[]>([])

/**
 * 根据路由动态生成权限树数据
 */
const initPermissionTreeFromRoutes = () => {
  const homeRoute = router.getRoutes().find(r => r.name === 'home')
  const children = (homeRoute?.children || []).filter(r => !!r.name)
  const topLevelGroups: Record<string, { label: string; children: { key: string; label: string }[] }> = {}

  // 简单分组策略：根据路径前缀或已知分组名称
  const inferGroup = (routeName: string | undefined, routePath: string, routeTitle?: any) => {
    if (routePath.startsWith('/home/system')) return '系统管理'
    if (routeName === 'dashboard') return '首页'
    if (routeName === 'profile') return '个人中心'
    return (routeTitle as string) || '其他'
  }

  permissionOptions.value = []

  children.forEach(r => {
    const group = inferGroup(r.name as string, r.path.startsWith('/') ? r.path : `/home/${r.path}`, r.meta?.title)
    if (!topLevelGroups[group]) {
      topLevelGroups[group] = { label: group, children: [] }
    }
    const option = { key: String(r.name), label: (r.meta?.title as string) || String(r.name) }
    topLevelGroups[group].children.push(option)
    permissionOptions.value.push({ key: option.key, label: option.label, parent: group })
  })

  permissionTreeData.value = Object.values(topLevelGroups).map(group => ({
    id: group.label,
    label: group.label,
    children: group.children.map(child => ({ id: child.key, label: child.label }))
  }))
}

// 本地存储键名
const rolePermissionStorageKey = (roleKey: string) => `role_permissions_key_${roleKey}`

// 获取某角色的权限 keys（从本地存储）
const getStoredPermissionKeys = (roleKey: string): string[] => {
  const raw = localStorage.getItem(rolePermissionStorageKey(roleKey))
  try {
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

// 保存某角色的权限 keys 到本地存储
const savePermissionKeys = (roleKey: string, keys: string[]) => {
  localStorage.setItem(rolePermissionStorageKey(roleKey), JSON.stringify(keys))
}

// 将权限 keys 转换为名称，供表格显示
const getRolePermissionNames = (roleKey: string) => {
  const keys = getStoredPermissionKeys(roleKey)
  if (!keys.length) return '-'
  const nameMap = new Map(permissionOptions.value.map(o => [o.key, o.label]))
  const seen = new Set<string>()
  const names: string[] = []
  keys.forEach(k => {
    const label = nameMap.get(k) || k
    if (!seen.has(label)) {
      seen.add(label)
      names.push(label)
    }
  })
  return names.join('、')
}

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  key: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '角色标识只能包含字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

/**
 * 获取角色列表
 */
const fetchRoles = async () => {
  loading.value = true
  try {
    const params: RoleListParams = {
      page: pagination.current,
      page_size: pagination.pageSize
    }
    
    const response = await getRoleList(params)
    
    if (response.code === 200) {
      roleList.value = response.data.results
      pagination.total = response.data.total
      
      // 获取每个角色的用户数量统计
      await fetchUserStats()
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (error: any) {
    console.error('获取角色列表失败:', error)
    ElMessage.error(error.response?.data?.message || '获取角色列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取用户统计信息
 */
const fetchUserStats = async () => {
  try {
    // 获取所有用户数据来统计各角色用户数量
    const userResponse = await userStore.getAdminUsers({ page_size: 1000 })
    const users = userResponse.results || []
    
    // 统计每个角色的用户数量
    const stats: Record<string, number> = {}
    users.forEach((user: any) => {
      const roleKey = user.role_key || 'unknown'
      stats[roleKey] = (stats[roleKey] || 0) + 1
    })
    
    userStats.value = stats
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

/**
 * 新增角色
 */
const handleAddRole = () => {
  dialogType.value = 'add'
  roleForm.id = undefined
  roleForm.name = ''
  roleForm.key = ''
  roleForm.description = ''
  roleForm.status = 0
  roleForm.sort = 0
  roleForm.permissions = []
  dialogVisible.value = true
}

/**
 * 编辑角色
 */
const handleEdit = async (row: Role) => {
  dialogType.value = 'edit'
  
  try {
    // 获取角色详情
    const response = await getRoleDetail(row.id)
    
    if (response.code === 200) {
      const roleData = response.data
      roleForm.id = roleData.id
      roleForm.name = roleData.name
      roleForm.key = roleData.key
      roleForm.description = roleData.description
      roleForm.status = roleData.status
      roleForm.sort = 0 // 后端暂无此字段
      // 从本地存储预填充该角色的权限（基于路由 name）
      const storedKeys = getStoredPermissionKeys(roleData.key)
      roleForm.permissions = storedKeys as any
      // 设置树的勾选状态
      requestAnimationFrame(() => {
        try {
          permissionTreeRef.value.setCheckedKeys(storedKeys)
        } catch (e) {}
      })
    } else {
      ElMessage.error(response.message || '获取角色详情失败')
      return
    }
  } catch (error: any) {
    console.error('获取角色详情失败:', error)
    ElMessage.error(error.response?.data?.message || '获取角色详情失败')
    return
  }
  
  dialogVisible.value = true
}

/**
 * 查看角色下的用户
 */
const handleViewUsers = async (row: Role) => {
  try {
    // 获取该角色下的所有用户
    const userResponse = await userStore.getAdminUsers({ 
      page_size: 1000,
      role_key: row.key 
    })
    const users = userResponse.results || []
    
    if (users.length === 0) {
      ElMessage.info(`角色 "${row.name}" 下暂无用户`)
      return
    }
    
    // 显示用户列表
    const userList = users.map((user: any) => user.username).join('\n')
    await ElMessageBox.alert(
      `角色 "${row.name}" 下的用户列表：\n\n${userList}`,
      '用户列表',
      {
        confirmButtonText: '确定',
        customClass: 'user-list-dialog'
      }
    )
  } catch (error: any) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

/**
 * 删除角色
 */
const handleDelete = async (row: Role) => {
  try {
    // 检查该角色下是否有用户
    const userCount = userStats.value[row.key] || 0
    let confirmMessage = `确定要删除角色 "${row.name}" 吗？`
    
    if (userCount > 0) {
      confirmMessage = `角色 "${row.name}" 下还有 ${userCount} 个用户，删除角色后这些用户将失去角色权限。确定要删除吗？`
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      '提示',
      { 
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    const response = await deleteRole(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchRoles()
      
      // 触发全局事件，通知其他组件角色数据已更新
      window.dispatchEvent(new CustomEvent('roleDataUpdated'))
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    
    submitLoading.value = true
    
    // 获取选中的权限（为路由 name 字符串）
    const checkedPermissions: string[] = permissionTreeRef.value.getCheckedKeys()
    roleForm.permissions = checkedPermissions as any
    
    if (dialogType.value === 'add') {
      const response = await createRole(roleForm)
      
      if (response.code === 200) {
        ElMessage.success('角色创建成功')
        dialogVisible.value = false
        fetchRoles()
        // 如填写了角色标识，则保存本地权限映射
        if (roleForm.key) {
          savePermissionKeys(roleForm.key, checkedPermissions)
        }
        
        // 触发全局事件，通知其他组件角色数据已更新
        window.dispatchEvent(new CustomEvent('roleDataUpdated'))
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    } else {
      if (!roleForm.id) {
        ElMessage.error('角色ID不能为空')
        return
      }
      
      const response = await updateRole(roleForm.id, roleForm)
      
      if (response.code === 200) {
        ElMessage.success('角色更新成功')
        dialogVisible.value = false
        fetchRoles()
        // 更新本地权限映射
        if (roleForm.key) {
          savePermissionKeys(roleForm.key, checkedPermissions)
        }
        
        // 触发全局事件，通知其他组件角色数据已更新
        window.dispatchEvent(new CustomEvent('roleDataUpdated'))
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('提交表单失败:', error)
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

/**
 * 分页大小变化
 */
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.current = 1
  fetchRoles()
}

/**
 * 当前页变化
 */
const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchRoles()
}

onMounted(() => {
  fetchRoles()
  initPermissionTreeFromRoutes()
  
  // 监听用户数据更新事件
  window.addEventListener('userDataUpdated', () => {
    fetchUserStats()
  })
})
</script>

<style scoped lang="scss">
.role-management {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);

  // 页面头部
  .page-header {
    margin-bottom: 32px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      padding: 0;

      .title-section {
        .page-title {
          font-size: 28px;
          font-weight: 700;
          color: #1e293b;
          margin: 0 0 8px 0;
          letter-spacing: -0.025em;
        }

        .page-subtitle {
          font-size: 14px;
          color: #64748b;
          margin: 0;
        }
      }

      .header-actions {
        .el-button {
          font-weight: 500;
          border-radius: 8px;
          padding: 12px 24px;
          
          .el-icon {
            margin-right: 6px;
          }
        }
      }
    }
  }

  // 主要内容区域
  .content-section {
    .table-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 0;
      }

      // 表格样式
      .el-table {
        :deep(.el-table__header-wrapper) {
          .el-table__header {
            th {
              border-bottom: 2px solid #e2e8f0;
              
              .cell {
                padding: 16px 12px;
              }
            }
          }
        }

        :deep(.el-table__body-wrapper) {
          .el-table__body {
            tr {
              &:hover {
                background: #f8fafc;
              }

              td {
                border-bottom: 1px solid #f1f5f9;
                
                .cell {
                  padding: 16px 12px;
                }
              }
            }
          }
        }

        // 角色名称样式
        .role-name {
          display: flex;
          align-items: center;
          gap: 8px;

          .role-icon {
            font-size: 16px;
            color: #3b82f6;
          }

          span {
            font-weight: 500;
            color: #1e293b;
          }
        }

        // 用户数量样式
        .user-count {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          padding: 4px 8px;
          background: #f0f9ff;
          border-radius: 6px;
          border: 1px solid #bae6fd;

          .user-icon {
            font-size: 14px;
            color: #0ea5e9;
          }

          .count-number {
            font-weight: 600;
            color: #0c4a6e;
            font-size: 14px;
          }

          .count-label {
            color: #64748b;
            font-size: 12px;
          }
        }

        // 时间信息样式
        .time-info {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #64748b;
          font-size: 13px;

          .time-icon {
            font-size: 14px;
          }
        }

        // 操作按钮样式
        .action-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;

          .el-button {
            border-radius: 6px;
            font-weight: 500;
            padding: 6px 12px;
            
            .el-icon {
              margin-right: 4px;
            }

            &.el-button--primary {
              &.is-plain {
                &:hover {
                  background: #3b82f6;
                  border-color: #3b82f6;
                  color: white;
                }
              }
            }

            &.el-button--danger {
              &.is-plain {
                &:hover {
                  background: #ef4444;
                  border-color: #ef4444;
                  color: white;
                }
              }
            }
          }
        }
      }

      // 分页样式
      .pagination-wrapper {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background: #fafbfc;
        display: flex;
        justify-content: flex-end;

        :deep(.el-pagination) {
          .el-pager {
            li {
              border-radius: 6px;
              margin: 0 2px;
              font-weight: 500;

              &.is-active {
                background: #3b82f6;
                color: white;
              }
            }
          }

          .btn-prev,
          .btn-next {
            border-radius: 6px;
            margin: 0 2px;
          }
        }
      }
    }
  }

  // 对话框样式
  :deep(.role-dialog) {
    .el-dialog__header {
      padding: 24px 24px 0;
      
      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 0 24px 24px;
    }
  }

  // 表单样式
  .role-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
      }

      .el-input,
      .el-textarea {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:hover {
            border-color: #9ca3af;
          }

          &.is-focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }
        }
      }

      .el-input-number {
        width: 100%;
        
        :deep(.el-input__wrapper) {
          border-radius: 8px;
        }
      }
    }

    // 权限树样式
    .permission-tree {
      border: 1px solid #d1d5db;
      border-radius: 8px;
      padding: 16px;
      background: #f9fafb;
      max-height: 300px;
      overflow-y: auto;

      .custom-tree {
        background: transparent;
        
        :deep(.el-tree-node) {
          .el-tree-node__content {
            padding: 8px 0;
            border-radius: 6px;
            margin: 2px 0;
            transition: background 0.3s ease;

            &:hover {
              background: rgba(59, 130, 246, 0.05);
            }

            .el-tree-node__label {
              font-size: 14px;
              color: #374151;
              font-weight: 500;
            }

            .el-checkbox {
              margin-right: 8px;
            }
          }

          .el-tree-node__children {
            .el-tree-node__content {
              padding-left: 24px;
              
              .el-tree-node__label {
                color: #6b7280;
                font-weight: 400;
              }
            }
          }
        }
      }
    }
  }

  // 对话框底部
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 10px 24px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .role-management {
    padding: 16px;

    .page-header {
      .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;

        .title-section {
          .page-title {
            font-size: 24px;
          }
        }

        .header-actions {
          .el-button {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }

    .content-section {
      .table-card {
        .el-table {
          // 移动端表格样式调整
          .action-buttons {
            flex-direction: column;
            gap: 4px;

            .el-button {
              font-size: 12px;
              padding: 4px 8px;
            }
          }
        }

        .pagination-wrapper {
          padding: 16px;
          
          :deep(.el-pagination) {
            .el-pagination__total,
            .el-pagination__sizes,
            .el-pagination__jump {
              display: none;
            }
          }
        }
      }
    }

    .role-form {
      .el-row {
        .el-col {
          &:not(:last-child) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>